package development.app;

import iplayparticle.view.iplayparticleResources;

import java.util.Vector;

import state.Clip;
import state.DrawListener;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.Sprite;
import state.TouchScreenListener;
import state.component.GameScrollBar;
import state.component.TextField;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.socket.MapDataPackage;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.NumberUtil;
import state.util.array.ByteArray;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.FrmDownloadResource;
import development.Global;
import development.bean.Category;
import development.group.FrmGroupMenu;
import development.group.FrmGroupNapXuAndExchangeGold;

public class FrmDanhSachVatPhamQuyDoi extends GameForm implements TouchScreenListener {
  public static final int IPLAY_CATEGOGRY_REQUEST = 700;
  public static final int IPLAY_CATEGOGRY_RESPONSE = 701;
  public static final int IPLAY_CONTENT_REQUEST = 702;
  public static final int IPLAY_CONTENT_RESPONSE = 703;
  public static final int IPLAY_ORDER_REQUEST = 704;
  public static final int IPLAY_ORDER_RESPONSE = 705;
  public static final int IPLAY_BILLING_LIST_REQUEST = 706;
  public static final int IPLAY_BILLING_LIST_RESPONSE = 707;

  private final String FIRST_CATEGORY_CODE = "WINPLAY_VAT_PHAM";

  private ImageText text8;
  private ImageText text11;
  private int categoryIndex;
  private String type;
  private Hashtable logAction = null;
  private int currentAction;

  private Vector categoriesPath;
  private int bottomParagraph;
  private int dy;
  private int defaultY;
  private int minTextY;

  private final int DEFAULT_TEXT_X = 5;
  private GameScrollBar scrollBar;
  private Clip textView; // Là khung nhìn để vẽ đoạn text ra

  private GameImage defaultImage;

  private Vector categories;

  private int percent;

  private TextField txtFullName;
  private TextField txtMobile;
  private TextField txtAddress;
  private TextField txtCMT;
  private TextField txtAmount;

  private boolean showOrderForm;
  private Category categoryBilling;
  private Hashtable parameters;
  private GameImage buttonImage;
  private Sprite betButtonSprite;

  private final String WAITING_MESSAGE = "Xin chờ trong giây lát...";

  private static GameForm singleton;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmDanhSachVatPhamQuyDoi();
    }
    return singleton;
  }

  public void init(Hashtable parameters1) {
    this.parameters = parameters1;
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    text11 = FontManager.getFont(FontManager.FONT_SIZE_11);

    txtFullName = new TextField(_manager, TextField.CONSTRAINT_ANY, null);
    txtFullName.setSize(GameConstants.SCREEN_WIDTH / 2 + 7, text8.getHeight());
    txtFullName.setAnchor(GameConstants.TOP_LEFT_ANCHOR);

    txtMobile = new TextField(_manager, TextField.CONSTRAINT_PHONE_NUMBER, null);
    txtMobile.setSize(GameConstants.SCREEN_WIDTH / 2 + 7, text8.getHeight());
    txtMobile.setAnchor(GameConstants.TOP_LEFT_ANCHOR);

    txtAddress = new TextField(_manager, TextField.CONSTRAINT_ANY, null);
    txtAddress.setSize(GameConstants.SCREEN_WIDTH / 2 + 7, text8.getHeight());
    txtAddress.setAnchor(GameConstants.TOP_LEFT_ANCHOR);

    txtCMT = new TextField(_manager, TextField.CONSTRAINT_NUMERIC, null);
    txtCMT.setSize(GameConstants.SCREEN_WIDTH / 2 + 7, text8.getHeight());
    txtCMT.setAnchor(GameConstants.TOP_LEFT_ANCHOR);

    txtAmount = new TextField(_manager, TextField.CONSTRAINT_NUMERIC, null);
    txtAmount.setSize(GameConstants.SCREEN_WIDTH / 2 + 7, text8.getHeight());
    txtAmount.setAnchor(GameConstants.TOP_LEFT_ANCHOR);
    txtAmount.setText("1");

    txtFullName.setVisible(false);
    txtAddress.setVisible(false);
    txtAmount.setVisible(false);
    txtCMT.setVisible(false);
    txtMobile.setVisible(false);
    txtFullName.setFocused(false);

    categories = new Vector();
    logAction = new Hashtable();
    categoriesPath = new Vector();
    currentAction = 1;
    type = "category";
    percent = 0;
    categoryIndex = 0;

    buttonImage = new GameImage(iplayparticleResources.image_button, null, null);
    betButtonSprite = new Sprite(null, _manager, 0, 0, Constants.TOP_LEFT_ANCHOR);
    betButtonSprite.setImage(buttonImage);
    betButtonSprite.setAnchor(Constants.TOP_LEFT_ANCHOR);
    betButtonSprite.setTouchScreenListener(this);
    betButtonSprite.setVisible(false);
    betButtonSprite.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        text8.drawString2(g, "Đặt hàng", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
      }
    });
    dy = DrawUtils.getTopBarHeight() + 1;

    textView = new Clip(DEFAULT_TEXT_X, dy, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - dy - 10); // Là khung nhìn để vẽ đoạn text ra
    scrollBar = new GameScrollBar(Constants.SCREEN_WIDTH - 5, 25, 5, Constants.SCREEN_HEIGHT - 50, textView, _manager);

    defaultImage = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "default_avatar.png");

    request(IPLAY_CATEGOGRY_REQUEST, new StringArray(new String[] { FIRST_CATEGORY_CODE },1));
    _manager.enableTouchPad();
  }

  public void draw(Graphics g) {
    DrawUtils.drawAppBackground(g);
    if (categories.isEmpty() && !showOrderForm) {
      text8.drawString2(g, WAITING_MESSAGE, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2, GameConstants.TOP_HCENTER_ANCHOR);
    }
    if (type.equals("category") || type.equals("content") && categories.size() != 0) {
      drawCategory(g);
    }
    if (showOrderForm) {
      drawOrder(g);
    }
    if (type.equals("billing_list")) {
      drawBillings(g);
    }

    DrawUtils.drawTopBar(g);
    drawMenu(g);

    text8.drawString2(g, GameStringUtils.join(categoriesPath, "-"), GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 5, GameConstants.TOP_HCENTER_ANCHOR);
    if (showOrderForm) {
      text8.drawString2(g, "Đặt hàng", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 5, GameConstants.TOP_HCENTER_ANCHOR);
    }
  }

  private void drawMenu(Graphics g) {
    if (type.equals("billing_list")) {
      DrawUtils.setBottomBar(_manager, null, null, "Trở về");
    }
    if (showOrderForm) {
      DrawUtils.getBottomBar(_manager).setCenterLabel("Chọn");
      DrawUtils.getBottomBar(_manager).setLeftLabel("Xem đơn hàng");
    }
    if (txtFullName.isFocused() || txtAddress.isFocused() || txtAmount.isFocused() || txtMobile.isFocused() || txtCMT.isFocused()) {
      DrawUtils.getBottomBar(_manager).setRightLabel("Xóa");
    } else {
      DrawUtils.getBottomBar(_manager).setRightLabel("Trở về");
    }
  }

  private void drawBillings(Graphics g) {
    int textY = dy;
    for (int i = 0; i < categories.size(); i++) {
      Category category = (Category) categories.elementAt(i);
      g.setColor(0xA9A9A9);
      g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
      g.drawRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
      text11.drawString3(g, "Đơn hàng " + category.exParam.elementAt(8), GameColor.WHITE_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      text8.drawString3(g, "Sản phẩm: " + category.exParam.elementAt(0), GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      text8.drawString3(g, "Giá: " + category.exParam.elementAt(1), GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      text8.drawString3(g, "Số lượng: " + category.exParam.elementAt(2), GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      int totalMoney = NumberUtil.parseInt((String) category.exParam.elementAt(1)) * NumberUtil.parseInt((String) category.exParam.elementAt(2));
      text8.drawString3(g, "Tổng tiền: " + totalMoney, GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      text8.drawString3(g, "Người mua: " + category.exParam.elementAt(4), GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      text8.drawString3(g, "Địa chỉ: " + category.exParam.elementAt(5), GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      text8.drawString3(g, "Số điện thoại: " + category.exParam.elementAt(6), GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      text8.drawString3(g, "CMND: " + category.exParam.elementAt(7), GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
      text8.drawString3(g, "Tình trạng: " + category.exParam.elementAt(9), GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
      textY = textY + 20;
      g.drawLine(0, textY, GameConstants.SCREEN_WIDTH, textY);
    }
    scrollBar.draw(g);
  }

  private void drawOrder(Graphics g) {
    int textY = dy;
    g.setColor(0xA9A9A9);
    g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
    g.drawRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
    text11.drawString2(g, "Sản phẩm", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, textY, GameConstants.TOP_HCENTER_ANCHOR);
    textY = textY + 20;
    text8.drawString2(g, "- " + categoryBilling.code, GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR);
    textY = textY + 20;
    text8.drawString2(g, "- Giá: " + categoryBilling.exParam.elementAt(0), GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR);
    textY = textY + 20;
    g.fillRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
    g.drawRect(0, textY, GameConstants.SCREEN_WIDTH, text11.getHeight());
    text11.drawString2(g, "Thông tin nhận hàng", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, textY, GameConstants.TOP_HCENTER_ANCHOR);
    textY = textY + 25;

    text8.drawString2(g, "Tên: ", GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR);
    txtFullName.setPosition(text8.stringWidth("Số lượng: ") + 5, textY);
    txtFullName.draw(g);
    textY = textY + 20;
    text8.drawString2(g, "Địa chỉ: ", GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR);
    txtAddress.setPosition(text8.stringWidth("Số lượng: ") + 5, textY);
    txtAddress.draw(g);
    textY = textY + 20;
    text8.drawString2(g, "Phone: ", GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR);
    txtMobile.setPosition(text8.stringWidth("Số lượng: ") + 5, textY);
    txtMobile.draw(g);
    textY = textY + 20;
    text8.drawString2(g, "Số CMND: ", GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR);
    txtCMT.setPosition(text8.stringWidth("Số lượng: ") + 5, textY);
    txtCMT.draw(g);
    textY = textY + 20;
    text8.drawString2(g, "Số lượng: ", GameColor.YELLOW_CODE, 5, textY, GameConstants.TOP_LEFT_ANCHOR);
    txtAmount.setPosition(text8.stringWidth("Số lượng: ") + 5, textY);
    txtAmount.draw(g);
    textY = textY + 20;
    betButtonSprite.setPosition(txtAmount.getRealX(), textY);
    if (categoryIndex == 0) {
      txtFullName.setFocused(true);
      txtAddress.setFocused(false);
      txtMobile.setFocused(false);
      txtCMT.setFocused(false);
      txtAmount.setFocused(false);
    }
    if (categoryIndex == 1) {
      txtFullName.setFocused(false);
      txtAddress.setFocused(true);
      txtMobile.setFocused(false);
      txtCMT.setFocused(false);
      txtAmount.setFocused(false);
    }
    if (categoryIndex == 2) {
      txtFullName.setFocused(false);
      txtAddress.setFocused(false);
      txtMobile.setFocused(true);
      txtCMT.setFocused(false);
      txtAmount.setFocused(false);
    }
    if (categoryIndex == 3) {
      txtFullName.setFocused(false);
      txtAddress.setFocused(false);
      txtMobile.setFocused(false);
      txtCMT.setFocused(true);
      txtAmount.setFocused(false);
    }
    if (categoryIndex == 4) {
      txtFullName.setFocused(false);
      txtAddress.setFocused(false);
      txtMobile.setFocused(false);
      txtCMT.setFocused(false);
      txtAmount.setFocused(true);
    }
    if (categoryIndex > 4) {
      txtFullName.setFocused(false);
      txtAddress.setFocused(false);
      txtMobile.setFocused(false);
      txtCMT.setFocused(false);
      txtAmount.setFocused(false);
    }
  }

  private void drawCategory(Graphics g) {
    int textY = dy;
    int index = 0;
    for (int i = 0; i < categories.size(); i++) {
      Category category = (Category) categories.elementAt(i);
      g.drawImage(category.image, 0, textY, GameConstants.TOP_LEFT_ANCHOR);
      if (!category.hasChild) {
        text8.drawString2(g, category.code, GameColor.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR);
        if (!category.exParam.isEmpty()) {
          text8.drawString2(g, "Giá: " + category.exParam.elementAt(0), GameColor.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() - 17, GameConstants.TOP_LEFT_ANCHOR);
        }
      } else {
        text8.drawString2(g, category.code, GameColor.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR);
      }
      if (categoryIndex == index) {
        g.setColor(0x53A4CF);
        g.fillRect(0, textY - 7, GameConstants.SCREEN_WIDTH, category.image.getHeight() + 25);
        g.drawImage(category.image, 0, textY, GameConstants.TOP_LEFT_ANCHOR);
        if (!category.hasChild) {
          text8.drawString2(g, category.code, GameColor.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR);
          if (!category.exParam.isEmpty()) {
            text8.drawString2(g, "Giá: " + category.exParam.elementAt(0), GameColor.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() - 17, GameConstants.TOP_LEFT_ANCHOR);
          }
        } else {
          text8.drawString2(g, category.code, GameColor.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR);
        }
      }
      if (!category.hasChild) {
        if (type.equals("content")) {
          text8.drawString2(g, "Mua hàng >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, textY + category.image.getHeight(), GameConstants.TOP_RIGHT_ANCHOR);
        } else {
          text8.drawString2(g, "Chi tiết >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, textY + category.image.getHeight(), GameConstants.TOP_RIGHT_ANCHOR);
        }
      }
      g.setColor(0xC0C0C0);
      g.drawLine(0, textY - 7, GameConstants.SCREEN_WIDTH, textY - 7);
      textY = textY + category.image.getHeight() + 25;
      index++;
    }
    bottomParagraph = textY;
    if (minTextY == -1) {
      minTextY = Constants.SCREEN_HEIGHT / 2 - bottomParagraph;
    }
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    MapDataPackage mapDataPackage = MapDataPackage.getMapPackage(dataPackage);
    type = mapDataPackage.popString("type");
    dy = DrawUtils.getTopBarHeight() + 1;
    Category category = null;
    GameGlobal.systemCanvas.hideAlert();
    switch (header) {
    case IPLAY_CATEGOGRY_RESPONSE:
      percent = percent + (int) mapDataPackage.popDouble("loading");
      String keyCategory = (String) mapDataPackage.getNames().elementAt(0);
      StringArray parameters1 = GameStringUtils.split(keyCategory, "@@@");
      category = new Category();
      category.id = parameters1.get(0);
      category.code = parameters1.get(1);
      category.hasChild = NumberUtil.parseInt(parameters1.get(2)) > 0;
      if (!categoriesPath.contains("Winplay Vật phẩm")) {
        categoriesPath.addElement("Winplay Vật phẩm");
      }
      ByteArray btImage = mapDataPackage.getByteArray(keyCategory);
      category.image = GameImage.createImage(btImage, 0, btImage.len());
      categories.addElement(category);
      break;
    case IPLAY_CONTENT_RESPONSE:
      percent = percent + (int) mapDataPackage.popDouble("loading");
      category = new Category();
      category.id = mapDataPackage.getString("id");
      category.code = mapDataPackage.getString("name");
      category.name = category.code;
      ByteArray btImage1 = mapDataPackage.getByteArray("avatarImage");
      category.image = GameImage.createImage(btImage1, 0, btImage1.len());
      category.exParam.addElement(mapDataPackage.getString("money"));
      categories.addElement(category);
      if (!categoriesPath.contains("Danh sách vật phẩm")) {
        categoriesPath.addElement("Danh sách vật phẩm");
      }
      break;
    case IPLAY_ORDER_RESPONSE:
      String status = mapDataPackage.getString("status");
      if (status.equals("1")) {
        Global.alert.showAlert3(this, GameAlert.OK_TYPE, StringArray.create2( "Bạn đã mua hàng thành công", "Chúng tôi sẽ chuyển hàng", "theo thông tin đã đăng ký" ));
      } else {
        Global.alert.showAlert3(this, GameAlert.OK_TYPE, StringArray.create1( "Hệ thống đang tạm thời", " gián đoạn trong ít phút" ));
      }
      break;
    case IPLAY_BILLING_LIST_RESPONSE:
      category = new Category();
      category.id = "";
      category.code = "";
      category.name = "";
      category.exParam.addElement(mapDataPackage.getString("content"));
      category.exParam.addElement(mapDataPackage.getString("money"));
      category.exParam.addElement(mapDataPackage.getString("amount"));
      category.exParam.addElement(mapDataPackage.getString("total_money"));
      category.exParam.addElement(mapDataPackage.getString("full_name"));
      category.exParam.addElement(mapDataPackage.getString("address"));
      category.exParam.addElement(mapDataPackage.getString("mobile"));
      category.exParam.addElement(mapDataPackage.getString("cmt"));
      category.exParam.addElement(mapDataPackage.getString("bill_date"));
      category.exParam.addElement(mapDataPackage.getString("status"));
      categories.addElement(category);
      if (!categoriesPath.contains("Danh sách đơn hàng")) {
        categoriesPath.addElement("Danh sách đơn hàng");
      }
      break;
    }
  }

  public void keyRepeated(int keyCode) {

    switch (keyCode) {
    case Key.DOWN:
      if (type.equals("billing_list")) {
        if (scrollBar.canScrollUp()) {
          dy -= 5;
        }
      }
      break;
    case Key.UP:
      if (type.equals("billing_list")) {
        if (scrollBar.canScrollDown()) {
          dy += 5;
        } else {
          dy = textView._y;
        }
      }
      break;
    }
  }

  public void keyReleased(int keyCode) {

    switch (keyCode) {
    case Key.DOWN:
      if (showOrderForm) {
        if (categoryIndex < 5) {
          categoryIndex++;
          dy -= 5;
        }
        if (categoryIndex == 5) {
          betButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Đặt hàng", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        } else {
          betButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Đặt hàng", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        }
        return;
      }
      if (type.equals("category") || type.equals("content") && !categories.isEmpty()) {
        if (categoryIndex < categories.size() - 1) {
          categoryIndex++;
        }
        if (bottomParagraph > (DrawUtils.getTopBarHeight() + Constants.SCREEN_HEIGHT / 2)) {
          if (type.equals("category") || type.equals("content")) {
            dy = dy - defaultImage.getHeight();
          }
        }
      }
      if (type.equals("billing_list")) {
        if (scrollBar.canScrollUp()) {
          dy -= 5;
        }
      }
      break;
    case Key.UP:
      if (showOrderForm) {
        if (categoryIndex > 0) {
          categoryIndex--;
          dy += 5;
        }
        if (categoryIndex == 5) {
          betButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Đặt hàng", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        } else {
          betButtonSprite.setDrawListener(new DrawListener() {
            public void paint(Sprite source, Graphics g) {
              text8.drawString2(g, "Đặt hàng", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
            }
          });
        }
        return;
      }
      if (type.equals("category") || type.equals("content") && !categories.isEmpty()) {
        if (categoryIndex > 0) {
          categoryIndex--;
        }
        if (dy < defaultY) {
          if (scrollBar.canScrollDown()) {
            dy += 5;
          } else {
            dy = textView._y;
          }
        }
      }
      if (type.equals("billing_list")) {
        if (scrollBar.canScrollDown()) {
          dy += 5;
        } else {
          dy = textView._y;
        }
      }
      break;
    case Key.FIRE:
      currentAction++;
      dy = DrawUtils.getTopBarHeight() + 1;
      if (type.equals("category")) {
        Category category = (Category) categories.elementAt(categoryIndex);
        if (category.hasChild) {
          if (!categoriesPath.contains(category.code)) {
            categoriesPath.addElement(category.code);
          }
          request(IPLAY_CATEGOGRY_REQUEST, new StringArray(new String[] { category.id },1));
          Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(10000);
          clearCategory();
        } else {
          request(IPLAY_CONTENT_REQUEST, category.id);
          Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(10000);
          clearCategory();
        }
      } else if (type.equals("content")) {
        if (!showOrderForm) {
          categoryBilling = (Category) categories.elementAt(categoryIndex);
          showOrderForm = true;
          txtFullName.setVisible(true);
          txtAddress.setVisible(true);
          txtAmount.setVisible(true);
          txtCMT.setVisible(true);
          txtMobile.setVisible(true);
          betButtonSprite.setVisible(true);
          clearCategory();
          return;
        }
        if (showOrderForm) {
          if (txtFullName.isFocused()) {
            txtFullName.pointerReleased(txtFullName, txtFullName.getRealX(), txtFullName.getRealY());
          } else if (txtAddress.isFocused()) {
            txtAddress.pointerReleased(txtAddress, txtAddress.getRealX(), txtAddress.getRealY());
          } else if (txtMobile.isFocused()) {
            txtMobile.pointerReleased(txtMobile, txtMobile.getRealX(), txtMobile.getRealY());
          } else if (txtCMT.isFocused()) {
            txtCMT.pointerReleased(txtCMT, txtCMT.getRealX(), txtCMT.getRealY());
          } else if (txtAmount.isFocused()) {
            txtAmount.pointerReleased(txtAmount, txtAmount.getRealX(), txtAmount.getRealY());
          }
          if (categoryIndex == 5) {
            if (txtFullName.getText().length() == 0) {
              Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn chưa nhập tên");
              return;
            }
            if (txtAddress.getText().length() == 0) {
              Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn chưa nhập địa chỉ");
              return;
            }
            if (txtMobile.getText().length() == 0) {
              Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn chưa nhập SĐT");
              return;
            }
            if (txtCMT.getText().length() == 0) {
              Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn chưa nhập số CMT");
              return;
            }
            if (txtAmount.getText().length() == 0) {
              Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn chưa nhập số lượng");
              return;
            }
            
            int amountInt = NumberUtil.parseInt(txtAmount.getText());
            if (amountInt == NumberUtil.ERROR_VALUE) {
              Global.alert.showAlert(this, GameAlert.OK_TYPE, "Số lượng phải là số");
              return;
            }
            
            int price = NumberUtil.parseInt((String) categoryBilling.exParam.elementAt(0));
            if (Global.currentUser.getMoney() < price * NumberUtil.parseInt(txtAmount.getText())) {
              Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create1( "Bạn không đủ $", "Bạn có muốn nạp $ không?" ), 100);
              return;
            }
            String fullName = txtFullName.getText();
            String address = txtAddress.getText();
            String mobile = txtMobile.getText();
            String cmt = txtCMT.getText();
            String amount = txtAmount.getText();

            request(IPLAY_ORDER_REQUEST, new StringArray(new String[] { categoryBilling.id, fullName, address, mobile, cmt, amount, (String) categoryBilling.exParam.elementAt(0) },7));
            Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(10000);
          }
        }
      }
      break;
    case Key.SOFT_RIGHT:
      if (showOrderForm) {
        if (txtFullName.isFocused()) {
          txtFullName.deleteLastChar();
          return;
        }
        if (txtAddress.isFocused()) {
          txtAddress.deleteLastChar();
          return;
        }
        if (txtMobile.isFocused()) {
          txtMobile.deleteLastChar();
          return;
        }
        if (txtCMT.isFocused()) {
          txtCMT.deleteLastChar();
          return;
        }
        if (txtAmount.isFocused()) {
          txtAmount.deleteLastChar();
          return;
        }
      }
      categoryIndex = 0;
      if (currentAction > 1) {
        if (type.equals("category")) {
          categoriesPath.removeElementAt(categoriesPath.size() - 1);
        }
        clearCategory();
        back();
      } else {
        if (Global.systemCanvas.lastState instanceof FrmDownloadResource) {
          GameGlobal.nextState(FrmGroupMenu.instance(), null);
        } else {
          GameGlobal.nextState(Global.systemCanvas.lastState, parameters);
        }
      }
      break;
    case Key.SOFT_LEFT:
      if (showOrderForm) {
        txtFullName.setFocused(false);
        txtAddress.setFocused(false);
        txtMobile.setFocused(false);
        txtCMT.setFocused(false);
        txtAmount.setFocused(false);

        txtFullName.setVisible(false);
        txtAddress.setVisible(false);
        txtAmount.setVisible(false);
        txtCMT.setVisible(false);
        txtMobile.setVisible(false);
        betButtonSprite.setVisible(false);

        // Danh sach don hang
        request(IPLAY_BILLING_LIST_REQUEST, "");
        showOrderForm = false;
        Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(10000);
        clearCategory();
      }
      break;
    default:
      if (txtFullName.isFocused()) {
        txtFullName.keyReleased1(keyCode);
      }
      if (txtAddress.isFocused()) {
        txtAddress.keyReleased1(keyCode);
      }
      if (txtMobile.isFocused()) {
        txtMobile.keyReleased1(keyCode);
      }
      if (txtCMT.isFocused()) {
        txtCMT.keyReleased1(keyCode);
      }
      if (txtAmount.isFocused()) {
        txtAmount.keyReleased1(keyCode);
      }
      break;
    }
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 99 || alertId == 0) {
      return;
    }
    if (alertId == 100 && eventType == GameAlert.YES_BUTTON) {
      FrmGroupNapXuAndExchangeGold.backForm = this;
      Global.nextState(FrmGroupNapXuAndExchangeGold.instance(), parameters);
    }
    if (eventType == GameAlert.OK_TYPE) {
      if (currentAction > 1) {
        clearCategory();
        back();
      }
    }
  }

  private void request(int header, StringArray parameters1) {
    DataPackage dataPackage = DataPackage.createDataPackage1(header);
    for (int i = 0; i < parameters1.len(); i++) {
      dataPackage.putString(parameters1.array[i]);
    }
    Global.appClient.write(dataPackage);
    logAction.put(String.valueOf(currentAction), buildLogAction(header, parameters1));
  }

  private void request(int header, String param) {
    request(header, new StringArray(new String[] { param },1));
  }

  private String buildLogAction(int requestType, StringArray parameters1) {
    StringBuffer sb = new StringBuffer();
    sb.append(String.valueOf(requestType));
    sb.append(",");
    for (int i = 0; i < parameters1.len(); i++) {
      sb.append(parameters1.array[i]);
      sb.append(",");
    }
    if (sb.toString().endsWith(",")) {
      sb.deleteCharAt(sb.length() - 1);
    }
    return sb.toString();
  }

  private void back() {
    if (type.equals("billing_list")) {
      type = "content";
      txtFullName.clearText();
      txtAddress.clearText();
      txtMobile.clearText();
      txtCMT.clearText();
      txtAmount.setText("1");
      showOrderForm = true;
      txtFullName.setVisible(true);
      txtAddress.setVisible(true);
      txtAmount.setVisible(true);
      txtCMT.setVisible(true);
      txtMobile.setVisible(true);
      betButtonSprite.setVisible(true);
    } else {
      showOrderForm = false;
      txtFullName.setVisible(false);
      txtAddress.setVisible(false);
      txtAmount.setVisible(false);
      txtCMT.setVisible(false);
      txtMobile.setVisible(false);
      betButtonSprite.setVisible(false);
      request(IPLAY_CATEGOGRY_REQUEST, new StringArray(new String[] { FIRST_CATEGORY_CODE },1));
      clearCategory();
      // currentAction--;
      // dy = DrawUtils.getTopBarHeight() + 1;
      // String values = (String) logAction.get(String.valueOf(currentAction));
      // String[] requestParams = StringUtils.split(values, ",");
      // int request = NumberUtil.parseInt(requestParams[0]);
      // request(request, new String[] { requestParams[1] });
    }
  }

  private void clearCategory() {
    categories.removeAllElements();
    categoriesPath.removeAllElements();
    categoryIndex = 0;
    percent = 0;
    dy = DrawUtils.getTopBarHeight() + 1;
  }

  public void destroy() {
    logAction = null;
    currentAction = 1;
    type = null;
    text8 = null;
    text11 = null;
    categories = null;
    categoriesPath = null;
    currentAction = 1;
    defaultImage = null;

    txtFullName = null;
    txtMobile = null;
    txtAddress = null;
    txtCMT = null;
    txtAmount = null;

    showOrderForm = false;
    categoryBilling = null;

    scrollBar = null;
    textView = null;
    parameters = null;

    betButtonSprite = null;
    buttonImage = null;
  }

  public void pointerDragged(Sprite source, int x, int y) {
  }

  public void pointerPressed(Sprite source, int x, int y) {
  }

  public void pointerReleased(Sprite source, int x, int y) {
  }
}
